# -*- encoding: utf-8 -*-
from datetime import datetime
from common.account.db import get_user
from common.es_core.report_creator import ReportCreator
from common.es_core.es_interface import es_search_interface
from common.dwc import shared_handler
from event_rule.dwc.up_marketing_rule import dwc_user_info as up_dwc_user_info
from common.dwc.qk.qk_handler import create_qk_user_info, get_qk_chn_list
from common.utils.maestro_exceptions import MaestroException, ERROR_USER_NOT_EXISTS


def get_user_info(game_id, user_id, time_range):
    assert game_id in ('dark2', 'dark3', 'dark4')
    user_pool = [user_id] if user_id else None
    report = ReportCreator.create_report(
        start_time=time_range[0], end_time=time_range[1], event_rule=up_dwc_user_info.USER_INFO_REPORT,
        index=game_id, user_pool=user_pool)
    report.update({
        'user_id': user_id,
        'last_login_chn': _get_last_active_chn(game_id, user_id),
        'active_at_back': _get_active_at_back(game_id, user_id, int(time_range[1].timestamp()))
    })
    return report


def get_top_hits(merchant_name, custom_filter, sort_key, sort_order='desc', size=1):
    query_dsl = {
        "query": {
            "bool": {
                "filter": custom_filter
            }
        },
        "size": size,
        "sort": [
            {sort_key: {"order": sort_order}}
        ]
    }
    resp_json = es_search_interface(merchant_name, query_dsl)
    hits = resp_json['hits']['hits']
    resp_items = []
    for hit in hits:
        resp_items.append(hit['_source'])
    return resp_items


def _get_last_active_chn(game_id, user_id):
    custom_filter = [
        {"term": {"_event_id": "active"}},
        {"term": {"_user_id": user_id}}
    ]
    hit_items = get_top_hits(game_id,
                             custom_filter=custom_filter,
                             sort_key='_event_time')
    if hit_items:
        return hit_items[0].get('_chn')


def _get_active_at_back(game_id, user_id, max_timestamp):
    custom_filter = [
        {"term": {"_user_id": user_id}},
        {"term": {"_event_id": "bet_order"}},
        {"range": {"_event_time": {"lt": max_timestamp}}}
    ]
    hit_items = get_top_hits(game_id,
                             custom_filter=custom_filter,
                             sort_key='_event_time')
    if hit_items:
        return hit_items[0].get('_event_time')


def manual_bind_chn(platform_id, user_id, channel):
    shared_handler.manual_bind_appid(platform_id, user_id, shared_handler.MarketingPlatformType.CHANNEL, channel)
    user = get_user(platform_id, user_id)
    today_start = datetime.now().replace(hour=0, minute=0, second=0, microsecond=0)
    # 以前註冊的用戶刷新一下數據
    if str(user['registered_at']) < str(today_start):
        qk_chn_list = get_qk_chn_list()
        if user['channel'] in qk_chn_list:
            create_qk_user_info(platform_id, user_pool=[user['user_id']],
                                start_time=user['registered_at'],
                                end_time=today_start)


def get_user_appid(platform_id, user_id):
    user = get_user(platform_id, user_id)
    if not user:
        raise MaestroException(ERROR_USER_NOT_EXISTS)
    return dict(s2s_appid=user['extra_info'] or '', agent_appid=user['agent_chn'] or '', qk_appid=user['qk_appid'] or '')
